var ValidateImg = function () {

    var basePath;
    var imgObj = $('#vi_img');
    var loadObj = $('#vi_load');
    var iconObj = $('#vi_icon');
    var textObj = $('#vi_text');
    var errorAlertObj = $('#errorAlert');

    var loadValidateImg = function (r) {
        imgObj.hide();
        loadObj.show();
        $.ajax({
            url: basePath + 'vi/ajax/loadValidateImg',
            type: 'POST',
            dataType: 'json',
            data: 'r=' + r,
            success: function (d) {
                loadObj.hide();
                if (d.msgid == 'ERR_VALIDATEIMG_REFRESH_TOO_MUCH') {
                    Alice.showDefaultWarningGrowl(d.msgdesc);
                } else {
                    errorAlertObj.hide();
                    imgObj.attr('src', basePath + d.validateimgPath);
                    imgObj.show();
                }
            },
            error: function () {
                Alice.showDefaultWarningGrowl("获取验证码失败");
            }
        });
    }

    var checkValidateImg = function () {
        $.ajax({
            url: basePath + 'vi/ajax/checkValidateImg',
            type: 'POST',
            dataType: 'json',
            data: 'vi_code=' + textObj.val(),
            success: function (d) {
                if (d.msgid == "SSSS") {
                    viewCheckResult("true");
                } else {
                    viewCheckResult("false");
                }
            },
            error: function () {
                Alice.showDefaultWarningGrowl("验证失败");
            }
        });
    }


    var viewCheckResult = function (isSuccess) {
        if ("true" == isSuccess) {
            iconObj.attr("class","fa fa-check");
            iconObj.attr("style","color:green");
        }else{
            iconObj.attr("class","fa fa-remove");
            iconObj.attr("style","color:red");
        }
    }

    var resetIcon = function () {
        iconObj.attr("class","fa fa-align-justify");
        iconObj.attr("style","color:#ccc");
    }

    return {
        init: function (base_path) {

            basePath = base_path;

            loadValidateImg(1);

            imgObj.click(function () {
                textObj.val("");
                resetIcon();
                loadValidateImg(1);
            });

            textObj.keyup(function (e) {
                if(e.which != 13){
                    if ($.trim(textObj.val()).length == 5) {
                        checkValidateImg();
                    }else{
                        resetIcon();
                    }
                }
            });
        }

    };

}();